/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.railway.app;

import com.railway.utils.CustomTableModel;
import com.railway.utils.RestServer;
import com.railway.utils.Toast;
import com.toedter.calendar.JDateChooser;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.print.PrinterException;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author Kenny
 */
public class StaffDetailPanel extends javax.swing.JPanel {

    Image imgArrow = new ImageIcon(this.getClass().getResource("/com/railway/image/arrow.png")).getImage();
    private ArrayList<String> colName;
    private ArrayList<ArrayList<Object>> rowData;
    private CustomTableModel ctmModel;
    private JSONObject json;
    private JSONArray jsonArray, jsonObject;
    private JDateChooser date = new JDateChooser();
    /**
     * Creates new form RoutePanel
     */
    public StaffDetailPanel() {
        initComponents();
        jcbIC.setSelected(true);
        initializeTable();
    }
    
      private void initializeTable() {
        new Thread() {
            @Override
            public void run() {
                colName = new ArrayList<>();
                colName.add("UserID");
                colName.add("IC");
                colName.add("FirstName");
                colName.add("LastName");
                colName.add("ContactNo");
                colName.add("Email");
                colName.add("Position");
                colName.add("YearEmployed");
                String data = RestServer.httpGet("staffDetail", "");
                try {
                    json = new JSONObject(data);
                    boolean error = json.optBoolean("error");
                    if (!error) {
                        int status = json.getInt("status");
                        if (status != 404) {
                            rowData = new ArrayList<>();
                            jsonArray = json.getJSONArray("content");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                ArrayList<Object> temp = new ArrayList<>();
                                temp.add(jsonArray.getJSONObject(i).getInt("uid"));
                                temp.add(jsonArray.getJSONObject(i).getString("icNo"));
                                temp.add(jsonArray.getJSONObject(i).getString("firstname"));
                                temp.add(jsonArray.getJSONObject(i).getString("lastname"));
                                temp.add(jsonArray.getJSONObject(i).getString("contactNo"));
                                temp.add(jsonArray.getJSONObject(i).getString("email"));
                                temp.add(jsonArray.getJSONObject(i).getString("position"));
                                temp.add(jsonArray.getJSONObject(i).getString("yearEmployed"));
                                rowData.add(temp);
                            }
                            ctmModel = new CustomTableModel(colName, rowData);
                            jtbStaffDetail.setModel(ctmModel);
                        }
                    } else {
                        Toast.makeText(getParent(), json.getString("message"), Toast.LENGTH_LONG).display();
                    }
                } catch (JSONException ex) {
                }
            }
        }.start();
    }
      
    private boolean checkIDUnique(String id){
        boolean validity = true;
        Object selectedObject;
        for(int i = 0 ; i < jtbStaffDetail.getRowCount() ; i++){
            selectedObject = (Object) jtbStaffDetail.getModel().getValueAt(i, 0);
            if(id.equals(selectedObject.toString())){
                   validity = false;
                   return validity;
            }
        }
        return validity;
    }
    
        private boolean checkICUnique(String ic){
        boolean validity = true;
        Object selectedObject;
        for(int i = 0 ; i < jtbStaffDetail.getRowCount() ; i++){
            selectedObject = (Object) jtbStaffDetail.getModel().getValueAt(i, 1);
            if(ic.equals(selectedObject.toString())){
                   validity = false;
                   return validity;
            }
        }
        return validity;
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        bgIndex = new javax.swing.ButtonGroup();
        jpDiscount = new javax.swing.JPanel();
        jpStaffInformation = new javax.swing.JPanel();
        jcbID = new javax.swing.JCheckBox();
        jcbIC = new javax.swing.JCheckBox();
        jtfICID = new javax.swing.JTextField();
        jbSearch = new javax.swing.JButton();
        jbPrint = new javax.swing.JButton();
        jspTableScroller = new javax.swing.JScrollPane();
        jtbStaffDetail = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jbtInitialize = new javax.swing.JButton();
        jpDiscountArrow = new javax.swing.JPanel(){
            protected void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(imgArrow, 0, 0, getWidth(), getHeight(), this);
            }
        };

        bgIndex.add(jcbIC);
        bgIndex.add(jcbID);

        setPreferredSize(new java.awt.Dimension(870, 460));
        setLayout(null);

        jpDiscount.setBackground(new java.awt.Color(220, 220, 220));
        jpDiscount.setLayout(null);

        jpStaffInformation.setBorder(javax.swing.BorderFactory.createTitledBorder("Staff Information"));

        jcbID.setText("ID");
        jcbID.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbIDActionPerformed(evt);
            }
        });

        jcbIC.setText("IC");
        jcbIC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbICActionPerformed(evt);
            }
        });

        jbSearch.setBackground(new java.awt.Color(46, 204, 113));
        jbSearch.setText("Add");
        jbSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbSearchActionPerformed(evt);
            }
        });

        jbPrint.setBackground(new java.awt.Color(46, 204, 113));
        jbPrint.setText("Print");
        jbPrint.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbPrintActionPerformed(evt);
            }
        });

        jtbStaffDetail.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jtbStaffDetail.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jspTableScroller.setViewportView(jtbStaffDetail);

        jButton1.setBackground(new java.awt.Color(46, 204, 113));
        jButton1.setText("Remove");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jbtInitialize.setBackground(new java.awt.Color(46, 204, 113));
        jbtInitialize.setText("Initialize");
        jbtInitialize.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtInitializeActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jpStaffInformationLayout = new javax.swing.GroupLayout(jpStaffInformation);
        jpStaffInformation.setLayout(jpStaffInformationLayout);
        jpStaffInformationLayout.setHorizontalGroup(
            jpStaffInformationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpStaffInformationLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpStaffInformationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpStaffInformationLayout.createSequentialGroup()
                        .addComponent(jcbIC, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jcbID, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, 198, Short.MAX_VALUE)
                        .addComponent(jtfICID, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jbSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(187, 187, 187))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpStaffInformationLayout.createSequentialGroup()
                        .addComponent(jbtInitialize)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
                .addComponent(jbPrint, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jpStaffInformationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jpStaffInformationLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jspTableScroller, javax.swing.GroupLayout.DEFAULT_SIZE, 818, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        jpStaffInformationLayout.setVerticalGroup(
            jpStaffInformationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpStaffInformationLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpStaffInformationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpStaffInformationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jtfICID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jbSearch))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpStaffInformationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jcbIC)
                        .addComponent(jcbID)))
                .addGap(331, 331, 331)
                .addGroup(jpStaffInformationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbPrint)
                    .addComponent(jButton1)
                    .addComponent(jbtInitialize))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(jpStaffInformationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpStaffInformationLayout.createSequentialGroup()
                    .addContainerGap(46, Short.MAX_VALUE)
                    .addComponent(jspTableScroller, javax.swing.GroupLayout.PREFERRED_SIZE, 309, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(44, Short.MAX_VALUE)))
        );

        jpDiscount.add(jpStaffInformation);
        jpStaffInformation.setBounds(10, 10, 850, 420);

        add(jpDiscount);
        jpDiscount.setBounds(0, 20, 870, 440);

        javax.swing.GroupLayout jpDiscountArrowLayout = new javax.swing.GroupLayout(jpDiscountArrow);
        jpDiscountArrow.setLayout(jpDiscountArrowLayout);
        jpDiscountArrowLayout.setHorizontalGroup(
            jpDiscountArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 150, Short.MAX_VALUE)
        );
        jpDiscountArrowLayout.setVerticalGroup(
            jpDiscountArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 20, Short.MAX_VALUE)
        );

        add(jpDiscountArrow);
        jpDiscountArrow.setBounds(720, 0, 150, 20);
    }// </editor-fold>//GEN-END:initComponents

    private void jcbIDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbIDActionPerformed
        jtfICID.setText(null);

    }//GEN-LAST:event_jcbIDActionPerformed

    private void jcbICActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbICActionPerformed
        jtfICID.setText(null);

    }//GEN-LAST:event_jcbICActionPerformed

    private void jbSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSearchActionPerformed
        if(jcbID.isSelected()){
            boolean proceed = checkIDUnique(jtfICID.getText().toString());
            if(proceed){
                String data = RestServer.httpGet("staffDetailById", jtfICID.getText());
                try {
                    json = new JSONObject(data);
                    boolean error = json.optBoolean("error");
                    if (!error) {
                        int status = json.getInt("status");
                            rowData = new ArrayList<>();
                            jsonArray = json.getJSONArray("content");
                            ArrayList<Object> temp = new ArrayList<>();
                            temp.add(jsonArray.getJSONObject(0).getInt("uid"));
                            temp.add(jsonArray.getJSONObject(0).getString("icNo"));
                            temp.add(jsonArray.getJSONObject(0).getString("firstname"));
                            temp.add(jsonArray.getJSONObject(0).getString("lastname"));
                            temp.add(jsonArray.getJSONObject(0).getString("contactNo"));
                            temp.add(jsonArray.getJSONObject(0).getString("email"));
                            temp.add(jsonArray.getJSONObject(0).getString("position"));
                            temp.add(jsonArray.getJSONObject(0).getString("yearEmployed"));
                            ctmModel.addRow(temp);
                            ctmModel.fireTableDataChanged();
                    }else{
                        Toast.makeText(getParent(), json.getString("message"), Toast.LENGTH_LONG).display();
                    }
                } catch (JSONException ex) {
                    Toast.makeText(getParent(), "Staff does not exist", Toast.LENGTH_LONG).display();
                }
            }else{
                Toast.makeText(getParent(), "The staff is already in the table", Toast.LENGTH_LONG).display();
            }
        }else{
            boolean proceed = checkICUnique(jtfICID.getText().toString());
            if(proceed){
                String data = RestServer.httpGet("staffDetailByIc", jtfICID.getText());
                try {
                    json = new JSONObject(data);
                    boolean error = json.optBoolean("error");
                    if (!error) {
                        int status = json.getInt("status");
                            rowData = new ArrayList<>();
                            jsonArray = json.getJSONArray("content");
                            ArrayList<Object> temp = new ArrayList<>();
                            temp.add(jsonArray.getJSONObject(0).getInt("uid"));
                            temp.add(jsonArray.getJSONObject(0).getString("icNo"));
                            temp.add(jsonArray.getJSONObject(0).getString("firstname"));
                            temp.add(jsonArray.getJSONObject(0).getString("lastname"));
                            temp.add(jsonArray.getJSONObject(0).getString("contactNo"));
                            temp.add(jsonArray.getJSONObject(0).getString("email"));
                            temp.add(jsonArray.getJSONObject(0).getString("position"));
                            temp.add(jsonArray.getJSONObject(0).getString("yearEmployed"));
                            ctmModel.addRow(temp);
                            ctmModel.fireTableDataChanged();
                    }else{
                        Toast.makeText(getParent(), json.getString("message"), Toast.LENGTH_LONG).display();
                    }
                } catch (JSONException ex) {
                    Toast.makeText(getParent(), "Staff does not exist", Toast.LENGTH_LONG).display();
                }
            }else{
                Toast.makeText(getParent(), "The staff is already in the table", Toast.LENGTH_LONG).display();
            }
        } 
    }//GEN-LAST:event_jbSearchActionPerformed

    private void jbPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbPrintActionPerformed
        if(jtbStaffDetail.getRowCount()>0){
            try{
                jtbStaffDetail.print();
            }catch(PrinterException ex){
                JOptionPane.showMessageDialog(null,"Print Problem");
            }
        }else{
            Toast.makeText(this, "There's no content to be printed", Toast.LENGTH_SHORT).display();
        }
                
              
    }//GEN-LAST:event_jbPrintActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        
        if (jtbStaffDetail.getSelectedRow() > -1) {
            Object id = jtbStaffDetail.getModel().getValueAt(jtbStaffDetail.getSelectedRow(), 0);
            int option = JOptionPane.showConfirmDialog(this, "Are you sure you want to remove this item?", "Remove Item", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (option == JOptionPane.YES_OPTION) {
                ctmModel.removeRow(jtbStaffDetail.getSelectedRow());
                ctmModel.fireTableDataChanged();
            }
        } else {
            Toast.makeText(this, "Please make selection first.", Toast.LENGTH_SHORT).display();
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jbtInitializeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtInitializeActionPerformed
        initializeTable();
    }//GEN-LAST:event_jbtInitializeActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup bgIndex;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jbPrint;
    private javax.swing.JButton jbSearch;
    private javax.swing.JButton jbtInitialize;
    private javax.swing.JCheckBox jcbIC;
    private javax.swing.JCheckBox jcbID;
    private javax.swing.JPanel jpDiscount;
    private javax.swing.JPanel jpDiscountArrow;
    private javax.swing.JPanel jpStaffInformation;
    private javax.swing.JScrollPane jspTableScroller;
    private javax.swing.JTable jtbStaffDetail;
    private javax.swing.JTextField jtfICID;
    // End of variables declaration//GEN-END:variables
}
